// https://leetcode.cn/problems/spiral-matrix/
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        // int nlayer = min(m / 2, n / 2);
        int nlayer = (min(m, n) + 1) / 2;
        vector<int> ans;
        for (int layer = 0; layer < nlayer; ++layer) {
            for (int j = layer; j < n - layer - 1; ++j) {
                ans.push_back(matrix[layer][j]);
            }
            for (int i = layer; i <= m - layer - 1; ++i) {
            // 加上最右下角那个数，防止因m - layer - 1 = layer被过滤
                ans.push_back(matrix[i][n - layer - 1]);
            }
            for (int j = n - layer - 2; j > layer && m - layer - 1 != layer; --j) { // 去除最右下角那个数
                ans.push_back(matrix[m - layer - 1][j]);
            }
            for (int i = m - layer - 1; i > layer && n - layer - 1 != layer; --i) {
                ans.push_back(matrix[i][layer]);
            }
        }
        return ans;
    }
};